/*
 * Copyright (c) 2006, 2021, webrx.cn All rights reserved.
 *
 */
package cn.webrx;

import java.io.*;

/**
 * <p>Project: javaseapp - ObjectStreamDemo
 * <p>Powered by webrx On 2021-08-13 17:16:00
 * <p>Created by IntelliJ IDEA
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 16
 */
public class ObjectStreamDemo {
    public static void main(String[] args) {
        //反序列化操作
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("stu.dat"))) {
            Student stu = (Student) ois.readObject();
            System.out.println(stu.getName());
            System.out.println(stu.getAddress());
            System.out.println(stu);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static void test(String[] args) {
        //var ss = "hello world";
        var st = new Student(1, "李四", 86, "河南郑州");
        //要求将st保存到文件中
        //ObjectInputStream 将对象实例保存到文件中
        //ObjectOutputStream 读取对象
        //对象流操作对象时，此对象的类必须实例序列化

        //对象序列化操作
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("stu.dat"))) {
            oos.writeObject(st);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //反序列化操作
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("stu.dat"))) {
            Student stu = (Student) ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }


    }
}
